<template>
  <div>

    <el-dialog v-model="formDelete.dialog" title="确认" width="30%" center>
      <template #default>您将删除条目:{{ formDelete.name }}</template>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="formDelete.dialog = false">取消</el-button>
        <el-button type="danger" @click="Confirmdelete">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <!--修改弹窗-->
    <el-dialog v-model="formEdit.dialog" :title="formEdit.PopupType" width="40%" center>
      <el-form :model="formEdit" label-width="120px" v-loading="loading">
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              action="/api/common/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="formEdit.image" class="avatar" :src="'/api/common/download?name='+formEdit.image" alt=""/>
            <el-icon v-else>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="formEdit.price"/>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="formEdit.name"/>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input v-model="formEdit.description" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="formEdit.dialog=false">取消</el-button>
        <el-button type="primary" @click="ConfirmEdit">确认</el-button>
      </span>
      </template>
    </el-dialog>
    <!--table显示-->

    <el-scrollbar>
      <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border
                :row-style="{height: '54.7px'}"
                style="font-size: 15px" stripe :data="tableData">
        <!--        <el-table-column prop="tid" label="图书类型编号" width="100"/>-->
        <el-table-column label="图片" width="auto">
          <template #default="scopeEdit">
            <div class="demo-image">
              <div class="block">
                <el-image style="width: 100px; height: 100px" :src="'/api/common/download?name='+scopeEdit.row.pic"
                          fit="cover"/>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="name" width="auto"/>
        <el-table-column label="用户名" prop="username" width="auto"/>
        <el-table-column label="介绍" prop="introduce" width="auto"/>
        <el-table-column label="销量" prop="sales" width="auto"/>
        <el-table-column label="评分">
          <template #default="scopeEdit">
            <el-rate
                v-model="scopeEdit.row.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value} 分"
            />
          </template>
        </el-table-column>


      </el-table>
    </el-scrollbar>

  </div>
</template>

<script lang="ts" setup>

import {onMounted, reactive, ref, watch} from "vue";
import {Delete, Edit, Operation, Plus, Search} from '@element-plus/icons-vue'


import {ElMessage, UploadProps} from "element-plus";
import {ElLoading} from "element-plus/es";
import {addMenuApi, deleteMenuApi, getDishApi, updateApi} from "@/api/Menu";
import {getToken} from "@/utils/auth";
import {getAllShopsApi} from "@/api/Shops";

const PopupType = ref(['添加', '编辑'])

//数据初始化
onMounted(() => {
  getTableData()
})

const rolesList = ref<any[]>([])
//分页
const page = reactive({
  current: 1,
  limit: 10,
  total: 0,
})


const tableData = ref([] as any)
const loading = ref(true)
const search = reactive({
  author: "",
  bookName: "",
  tid: ""
})

function getTableData() {
  getAllShopsApi().then((response: any) => {
    tableData.value = []
    if (response.code === 200) {
      response.data.forEach((item: any) => {
        if (item.name != null) {
          tableData.value.push(item)
        }

      })


    } else {
      ElMessage.warning(response.message)
    }
    loading.value = false
  }).catch(function (res) {
    loading.value = false
    ElMessage.error("页面加载失败")
  })
}


//添加修改数据初始化
const BtnConfirmAble = ref(true)
const formEdit = reactive({
  businessId: 0,
  description: "",
  id: 0,
  image: "",
  name: "",
  price: 0,
  PopupType: "",
  dialog: false
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  formEdit.image = URL.createObjectURL(uploadFile.raw!)
  console.log(response)
  if (response.code == 200) {
    formEdit.image = response.data
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是JPG格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}


//弹窗展示编辑表格
function editInitialize(row: any) {
  Object.assign(formEdit, row);
  formEdit.dialog = true;
  formEdit.PopupType = PopupType.value[1];
}


function ConfirmEdit() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0,0,0,0.7)',
  })
  BtnConfirmAble.value = true
  if (formEdit.PopupType == PopupType.value[0]) {
    addMenuApi(formEdit)
        .then(function (response: any) {
          if (response.code === 200) {
            getTableData()
            formEdit.dialog = false;
            ElMessage.success(response.message)
          } else {
            ElMessage.warning("名称已使用")
          }
          loading.close()
        }).catch(response => {
      ElMessage.error("修改失败")
      loading.close()
    })
  } else {
    updateApi(formEdit).then(function (response: any) {
      if (response.code === 200) {
        getTableData()
        formEdit.dialog = false;
        ElMessage.success(response.message)
      } else {
        ElMessage.warning(response.message)
      }
      loading.close()
    }).catch(() => {
      ElMessage.error("修改失败")
      loading.close()
    })
  }

}


//添加系统用户


function addInitialize() {
  Object.assign(formEdit, {
    businessId: getToken(),
    description: "",
    id: null,
    image: "",
    name: "",
    price: 0,
    PopupType: PopupType.value[0],
    dialog: true
  });
}

const formDelete = reactive({
  id: -1,
  name: '',
  dialog: false
})

//删除
function deleteInitialize(row: any) {
  formDelete.id = row.id
  formDelete.name = row.name
  formDelete.dialog = true;
}

function Confirmdelete() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0,0,0,0.7)',
  })
  BtnConfirmAble.value = true
  deleteMenuApi(formDelete.id)
      .then(function (response: any) {
        if (response.code === 200) {
          getTableData()
          ElMessage.success("删除成功")
        } else {
          ElMessage.error(response.message)
        }
        loading.close()
      }).catch(response => {
    ElMessage.error("删除失败")
    loading.close()
  })
}

const formLabelWidth = '140px'
const inputSize = 'default'

</script>
